<template>
  <div>
    <div>
    <crumbs :BreadCrumb="BreadCrumb"></crumbs>

      <div class="box_flex_r">
        <div>
          <el-form :inline="true" :model="searchList" class="demo-form-inline">
            <div>

              <el-form-item label="套餐名称">
                <el-input
                    v-model="searchList.packageName"
                    placeholder="套餐名称"
                ></el-input>
              </el-form-item>
              <el-form-item label="体检类型">
                <el-select
                    v-model="searchList.packageType"
                    placeholder="体检类型"
                    :label-width="formLabelWidth"
                    clearable
                >
                  <el-option label="未指定" value=""></el-option>
                  <el-option v-for="(v,i) in dict.tyType" :key="i" :label="v.itemName" :value="v.itemCode"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button @click="getList" class="query">查询</el-button>
              </el-form-item>
              <el-form-item class="staff_form_btn">
                <el-button type="success" @click="addOndialogFormcontent">新建套餐</el-button>
              </el-form-item>
            </div>

          </el-form>
        </div>
        <el-divider></el-divider>
        <div class="wi100">
          <el-table :data="Packagelist" border>
            <el-table-column prop="packageCode" label="套餐编号" width="80">
            </el-table-column>
            <el-table-column prop="packageName" label="套餐名称" width="220">
            </el-table-column>
            <el-table-column width="80" prop="searchChar" label="代码">
            </el-table-column>
            <el-table-column prop="packageType" label="体检类型">
              <template slot-scope="scope">
                {{ formatPackageType(scope.row.packageType) }}
              </template>
            </el-table-column>
            <el-table-column prop="applyTo" label="适用范围">
              <template slot-scope="scope">
                {{ scope.row.applyTo | applyod }}
              </template>
            </el-table-column>
            <el-table-column prop="price" label="单价">
              <template slot-scope="scope">
                {{ scope.row.price|numFilter }}
              </template>
            </el-table-column>
            <el-table-column prop="unitName" label="单位名称" width="150"></el-table-column>
            <el-table-column prop="groupDiscount" label="团体是否折扣" width="120" align="center">
              <template slot-scope="scope">
                <el-checkbox
                    :disabled="scope.row.groupDiscount == 0 ? false : true"
                    :true-label="1"
                    :false-label="0"
                ></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column label="有效时间" width="150">
              <template slot-scope="scope">
                <span>{{ scope.row.validTo | formatDate }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="是否启用" align="center">
              <template slot-scope="scope">
                <el-checkbox
                    v-model="scope.row.status"
                    disabled
                    :true-label="1"
                    :false-label="0"
                ></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="editTime" label="编辑时间" width="220">
              <template slot-scope="scope">
                <span>{{ scope.row.editTime | formatDate }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="editor" label="编写者"></el-table-column>
            <el-table-column width="200" prop="address" label="操作" fixed="right">
              <template slot-scope="scope">
                <el-button
                    @click="ondialogFormcontent(scope.row)"
                    type="primary"
                    size="small"
                >编辑
                </el-button>
                <el-button @click="remove(scope.row)" type="danger" size="small"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="block">
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="searchForm.pageNo"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="searchForm.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
          >
          </el-pagination>
        </div>
      </div>
    </div>
    <!-- 编辑体检项目信息弹框 -->
    <el-dialog
        title="编辑套餐"
        :visible.sync="dialogFormcontent"
        :append-to-body="true"
        width="90%"
        class="top_dialog"
    >
      <div>
        <div class="box_flex">
          <div>
            <el-form
                :inline="true"
                :model="formEdit"
                class="demo-form-inline"
                label-position="left"
                ref="EditForm"
            >
              <div>
                <el-form-item :label-width="formLabelWidth" label="套餐名称">
                  <el-input
                      v-model="formEdit.packageName"
                      placeholder="套餐名称"
                  ></el-input>
                </el-form-item>
                <el-form-item :label-width="formLabelWidth" label="编码">
                  <el-input
                      v-model="formEdit.packageCode"
                      placeholder="编码"
                  ></el-input>
                </el-form-item>
                <el-form-item :label-width="formLabelWidth" label="体检类型">
                  <el-select
                      class="form_select"
                      v-model="formEdit.packageType"
                      size="medium"
                      placeholder="体检类型"
                  >
                    <el-option v-for="(v,i) in dict.tyType" :key="i" :label="v.itemName"
                               :value="v.itemCode"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item :label-width="formLabelWidth" label="适用范围">
                  <el-select
                      class="form_select"
                      v-model="formEdit.applyTo"
                      size="medium"
                      placeholder="适用范围"
                      @change="appto"
                  >
                    <el-option v-for="(v,i) in optionsSex" :key="i" :label="v.label" :value="v.value"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item :label-width="formLabelWidth" label="代码">
                  <el-input
                      v-model="formEdit.searchChar"
                      placeholder="代码"
                  ></el-input>
                </el-form-item>
              </div>

              <div>
                <el-form-item :label-width="formLabelWidth" label="单位名称">
                  <el-input
                      v-model="formEdit.unitName"
                      placeholder="单位名称"
                  ></el-input>
                </el-form-item>
                <el-form-item :label-width="formLabelWidth" label="价格">
                  <el-input
                      v-model="formEdit.price"
                      placeholder="价格"
                  ></el-input>
                </el-form-item>
                <el-form-item :label-width="formLabelWidth" label="有效期限">
                  <el-date-picker
                      v-model="formEdit.validTo"
                      type="datetime"
                      placeholder="选择日期时间"
                  >
                  </el-date-picker>
                </el-form-item>

                <el-form-item :label-width="formLabelWidth" label="">
                  <el-checkbox-group v-model="formEdit.groupDiscount">
                    <el-checkbox
                        :true-label="1"
                        :false-label="0"
                        class="info_sel_r_group"
                        label="团体是否折扣"
                        name="type"
                    ></el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
                <el-form-item :label-width="formLabelWidth" label="">
                  <el-checkbox-group v-model="formEdit.status">
                    <el-checkbox
                        :true-label="1"
                        :false-label="0"
                        class="info_sel_r_group"
                        label="是否启用"
                        name="type"
                    ></el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </div>
            </el-form>
          </div>
          <div class="flex_btn">
            <el-button type="primary" @click="copytaocan = true"
            >复制套餐
            </el-button
            >
          </div>
        </div>
        <el-divider></el-divider>
      </div>
      <div class="box_flex">
        <!-- 左侧目录 -->
        <div class="aside_box">
          <departments
              :list="departmentList"
              @getcatatlogue="getcatatlogue"
          ></departments>
        </div>
        <!-- 左侧表格 -->
        <div class="dialog_tab_l">
          <div>
            <el-form
                size="mini"
                :inline="true"
                :model="formInline"
                class="demo-form-inline"
            >
              <el-form-item label="">
                <el-input
                    v-model="formInline.user"
                    placeholder="关键字查询"
                ></el-input>
              </el-form-item>
              <el-button @click="changeleft" size="small">查询</el-button>
            </el-form>
          </div>
          <div>
            <el-table
                :data="tableDatalist"
                border
                tooltip-effect="dark"
                height="50vh"
                ref="multipleTableleft"
                @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="itemName" label="检查项目" width="220">
              </el-table-column>
              <el-table-column width="80" prop="address" label="代码">
              </el-table-column>
              <el-table-column width="80" prop="applyTo" label="适用范围">
                <template slot-scope="scope">
                  {{ scope.row.applyTo |applyod }}
                </template>
              </el-table-column>
              <el-table-column width="80" prop="price" label="价格">
                <template slot-scope="scope">
                  {{ scope.row.price|numFilter }}
                </template>
              </el-table-column>
              <el-table-column prop="deptName" label="科室" width="80">
              </el-table-column>
              <el-table-column width="80" prop="itemCode" label="序号">
              </el-table-column>
            </el-table>
          </div>
        </div>
        <!-- 中间两个按钮 -->
        <div class="dialog_tab_btn">
          <div>
            <el-button type="primary" @click="addlist">></el-button>
          </div>
          <div>
            <el-button type="primary" @click="removelist">&lt;</el-button>
          </div>
        </div>
        <!-- 右侧表格 -->
        <div class="dialog_tab_r">
          <div>
            <div class="dialog_tab_r_title">
              <span>已选套餐的项目{{ this.tableDataright.length }}</span>
              <!-- <span>价格合计 {{ rightListPrice | numFilter }}</span> -->
              <span>价格合计 {{ reversedMessage|numFilter }}</span>
            </div>
          </div>
          <div>
            <el-table
                :data="tableDataright"
                border
                height="50vh"
                tooltip-effect="dark"
                ref="multipleTableright"
                @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="itemName" label="检查项目" width="220">
              </el-table-column>
              <el-table-column width="80" prop="address" label="代码">
              </el-table-column>
              <el-table-column width="80" prop="applyTo" label="适用范围">
                <template slot-scope="scope">
                  {{ scope.row.applyTo | applyod }}
                </template>
              </el-table-column>
              <el-table-column width="80" prop="price" label="定价">
                <template slot-scope="scope">
                  {{ scope.row.price|numFilter }}
                </template>
              </el-table-column>
              <el-table-column prop="deptName" label="科室" width="80">
              </el-table-column>
              <el-table-column width="80" prop="itemCode" label="序号">
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editPackage('EditForm')"
        >保 存
        </el-button>
        <el-button @click="dialogFormcontent = false">取 消</el-button>
      </div>

      <el-dialog title="选择套餐" :visible.sync="copytaocan" append-to-body>
        <el-form :model="copytc">
          <el-form-item
              label=""
              :label-width="formLabelWidth"
              style="width: 200px"
          >
            <el-input v-model="copytc.name" placeholder="关键字"></el-input>
          </el-form-item>
        </el-form>
        <el-table
            ref="multipleTable"
            :data="medicalpackage"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleSelectionChange"
            border
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="packageType" label="体检类型">
            <!-- <template slot-scope="scope">{{ formatPackageType(scope.row.packageType) }}</template> -->
          </el-table-column>
          <el-table-column prop="packageCode" label="套餐编号">
          </el-table-column>
          <el-table-column prop="packageName" label="体检套餐">
          </el-table-column>
          <el-table-column prop="price" label="套餐价格">
            <template slot-scope="scope">
              {{ scope.row.price|numFilter }}
            </template>
          </el-table-column>
          <el-table-column prop="applyTo" label="适用范围">
            <template slot-scope="scope">
              {{
                scope.row.applyTo |applyod
              }}
            </template>
          </el-table-column>
          <el-table-column prop="code" label="代码" width="50"></el-table-column>
          <el-table-column label="编辑时间" prop="editTime">
            <template slot-scope="scope">{{ scope.row.editTime| formatDate }}</template>
          </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="showview">确 定</el-button>
          <el-button @click="copytaocan = false">取 消</el-button>
        </div>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import crumbs from "../../views/Crumbs.vue";
import administrative from "../common/administrative.vue";
import catalogue from "../common/catalogue.vue";
import departments from "../common/departments.vue";
import {formatTimeToStr} from "../../common/utils/date.js";
import {optionsSex} from "../../common/utils/constant.js";

export default {
  components: {
    crumbs,
    administrative,
    catalogue,
    departments
  },
  data() {
    return {
      optionsSex:optionsSex,
      dict: {},
      rightListPrice: 0,
      // 选择套餐表格
      medicalpackage: [],
      copytc: {},
      copytaocan: false,
      searchForm: {},
      pageSize: 10,
      pageNo: 1,
      total: 0,
      id: "",
      formEdit: {
        packageType: "",
        applyTo: 1,
        status: "",
        groupDiscount: "",
      },
      formLabelWidth: "80px",
      dialogFormcontent: false,
      BreadCrumb: [
        {path: "", name: "基础管理"},
        {path: "/basic/physicalSet", name: "体检套餐设置"},
      ],
      data: [],
      searchList: {
        // validTo: 0,
        // status: 0,
      },
      formInline: {
        name: "123",
        type: "123",
      },
      tableDatalist: [],
      tableDataright: [],
      tableData: [],
      // leftlist: [],
      Packagelist: [],
      datalist: [],
      departmentList: [],
    };
  },
  filters: {
    formatDate: function (time) {
      if (time != null && time !== "") {
        var date = new Date(time);
        return formatTimeToStr(date, "yyyy-MM-dd hh:mm");
      } else {
        return "";
      }
    },
    numFilter(value) {
      let realVal = "";
      if (!isNaN(value) && value !== "") {
        // 截取当前数据到小数点后两位,改变toFixed的值即可截取你想要的数值
        realVal = parseFloat(value).toFixed(2);
      } else {
        realVal = "--";
      }
      return realVal;
    },
    applyod(value) {
      const ss = {}
      optionsSex.forEach(v => {
        ss[v.value] = v.label
      })
      return ss[value]
    }
  },
  computed: {
    reversedMessage: function () {
      let num = 0
      this.tableDataright.forEach((res) => {
        num += res.price;
      })
      return num
    }
  },
  watch: {
    reversedMessage() {
      let realVal = "";
      if (!isNaN(this.reversedMessage) && this.reversedMessage !== "") {
        // 截取当前数据到小数点后两位,改变toFixed的值即可截取你想要的数值
        realVal = parseFloat(this.reversedMessage).toFixed(2);
      } else {
        realVal = "--";
      }
      this.formEdit.price = realVal
    },
  },
  created() {
    this.searchDictList();
    this.getPackageList();
    this.getDepartmentList()
    // this.leftlist()
    this.getExamItemList();
    // 渲染赋值页面
    this.onCopy();
  },
  methods: {
    appto() {
      this.getExamItemList()
      this.onCopy()
    },
    searchDictList() {
      this.$axios.searchDictList({
        codes: ["tyType"],
      }).then((res) => {
        if (res.code === "00000") {
          res.data.forEach(v => {
            this.dict[v.dictCode] = v.items
            console.log(this.dict);

          })
        }
      });
    },
    formatPackageType(v) {
      let i = 0
      this.dict.tyType.forEach((item, index) => {
        if (item.itemCode == v) {
          i = index
        }
      })
      if (this.dict) {
        return this.dict["tyType"][i].itemName
      } else {
        return v
      }
    },
    getDepartmentList() {
      let that = this;
      this.$axios.getDepartTreeList({}).then((res) => {
        if (res.code == "00000") {
          that.departmentList = res.data;
        }
      });
    },
    // 添加项目
    addlist() {
      let left = this.$refs.multipleTableleft.selection;
      left.forEach((res) => {
        let num = 0;
        this.tableDataright.forEach((ress) => {
          if (ress.id == res.id) {
            num = num + 1;
          }
        });
        if (num == 0) {
          this.tableDataright.push(res);
        } else {
          this.$message({
            type: "success",
            message: "重复项目无法添加",
          });
        }
      });
      this.rightListPrice = 0;
      this.tableDataright.forEach((res) => {
        this.rightListPrice += res.price;
      });
      // console.log(this.tableDataright, "left");
      this.$refs.multipleTableleft.clearSelection();
    },
    removelist() {
      let right = this.$refs.multipleTableright.selection;
      console.log(right);
      for (let index = 0; index < right.length; index++) {
        this.tableDataright.forEach((value, index, array) => {
          right.forEach((res) => {
            if (value.id == res.id) {
              array.splice(index, 1);
            }
          });
        });
      }
      this.rightListPrice = 0;
      this.tableDataright.forEach((res) => {
        this.rightListPrice += res.price;
      });
      this.$refs.multipleTableright.clearSelection();
    },
    // 左侧列表
    getExamItemList() {
      this.$axios.examItemList({
        pageSize: 1000,
        applyTo: this.formEdit.applyTo
      }).then((res) => {
        if (res.code == "00000") {
          console.log(res);
          this.tableDatalist = res.data.records;
        }
      });
    },
    // 列表刷新
    getPackageList() {
      this.$axios
          .readPackageList({
            pageNo: this.pageNo,
            pageSize: this.pageSize,
          })
          .then((res) => {
            if (res.code == "00000") {
              this.Packagelist = res.data.records;
              this.total = res.data.total;
            }
          });
    },
    // 提交and修改
    editPackage(formName) {
      this.datalist = [];
      // console.log(this.tableDataright);
      this.tableDataright.forEach((res) => {
        if (this.id != "") {
          this.datalist.push({itemId: res.id, packageId: this.id});
        } else {
          this.datalist.push({itemId: res.id});
        }
      });
      this.formEdit.pbPackageItemsList = this.datalist;
      console.log(this.formEdit);
      console.log(this.tableDataright);
      //去除无用字段
      delete this.formEdit.pbExamItemsList;
      delete this.formEdit.pageNo;
      delete this.formEdit.pageSize;
      console.log(this.formEdit);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.id == null) {
            this.$axios.addPackage({...this.formEdit}).then((res) => {
              if (res.code == "00000") {
                this.$message({
                  type: "success",
                  message: res.msg,
                });
                this.dialogFormcontent = false;
                this.getPackageList();
              }
            });
          } else {
            // 更新
            // if (this.datalis.length == 0) {
            //   this.$message({
            //     type: "success",
            //     message: "至少选择一个套餐",
            //   });
            // }
            this.$axios
                .updatePackage({...this.formEdit, id: this.id})
                .then((res) => {
                  if (res.code == "00000") {
                    this.$message({
                      type: "success",
                      message: res.msg,
                    });
                    this.dialogFormcontent = false;
                    this.getPackageList();
                  }
                });
          }
        }
      });
    },
    // 删除
    remove(id) {
      this.$confirm("此操作将删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$axios
            .deletePackageById({
              pbPackagesId: id.id,
            })
            .then((res) => {
              if (res.code == "00000") {
                this.$message({
                  type: "success",
                  message: res.msg,
                });
                this.getPackageList();
              }
            });
      });
    },
    // 查询
    getList() {
      delete this.searchList.validTo;
      this.$axios.readPackageList(this.searchList).then((res) => {
        if (res.code == "00000") {
          this.Packagelist = res.data.records;
          this.total = res.data.total;
        }
      });
    },
    // onSearch() {
    //   console.log({...this.searchForm});
    //   this.$axios.readPackageList({
    //     ...this.searchForm
    //   }).then(res => {
    //     if (res.code == '00000') {
    //       this.$message({
    //         type: 'success',
    //         message: res.msg
    //       })
    //       this.getPackageList()
    //     }
    //   })
    // },
    // 信息添加或修改的左侧树形图
    leftlist() {
      // this.$axios.getdepartmentList(
      //     {
      //       id: '1'
      //     }
      // ).then(res => {
      //   console.log(123);
      //   console.log(res);
      //   this.leftlist = res.data
      // })
    },
    // 复制
    onCopy() {
      this.$axios.readPackageList({
        applyTo: this.formEdit.applyTo
      }).then((res) => {
        if (res.code == "00000") {
          this.medicalpackage = res.data.records;
          // console.log(res.data.records);
        }
      });
      this.rightListPrice = 0;
      this.tableDataright.forEach((res) => {
        this.rightListPrice += res.price;
      });
    },
    showview() {
      let idea = this.$refs.multipleTable.selection;
      this.$axios
          .getPackageById({
            pbPackagesId: idea[0].id,
          })
          .then((res) => {
            if (res.code == "00000") {
              this.formEdit = res.data;
              this.tableDataright = res.data.pbExamItemsList;
            }
          });
      this.copytaocan = false;
    },
    // 编辑 反显
    ondialogFormcontent(row) {
      this.id = row.id;
      this.$axios
          .getPackageById({
            pbPackagesId: row.id,
          })
          .then((res) => {
            if (res.code == "00000") {
              this.formEdit = res.data;
              this.tableDataright = res.data.pbExamItemsList;
              this.getPackageList();
            }
          });
      this.rightListPrice = 0;
      this.tableDataright.forEach((res) => {
        this.rightListPrice += res.price;
      });
      this.dialogFormcontent = true;
    },
    // 添加
    addOndialogFormcontent() {
      // 清空数据
      this.formEdit = {
        packageType: "",
        applyTo: 1,
        status: "",
        groupDiscount: "",
      };
      this.tableDataright = [];
      this.id = null;
      this.rightListPrice = 0;
      this.tableDataright.forEach((res) => {
        this.rightListPrice += res.price;
      });
      this.dialogFormcontent = true;
    },
    // 每页几条
    handleSizeChange(val) {
      console.log(val);
      this.pageSize = val;
      this.getPackageList();
    },
    // 第几页
    handleCurrentChange(val) {
      console.log(val);
      this.pageNo = val;
      this.getPackageList();
    },
    getcatatlogue(e) {
      // console.log(e);
      this.$axios
          .examItemList({
            deptId: e.id,
            applyTo: this.formEdit.applyTo,
            pageSize: 1000
          })
          .then((res) => {
            this.tableDatalist = res.data.records;
            // console.log(res, "根据id获取");
          });
    },
    handleSelectionChange() {
    },
    changeleft() {
      this.$axios
          .examItemList({
            itemName: this.formInline.user,
            applyTo: this.formEdit.applyTo,
            pageSize: 1000
          })
          .then((res) => {
            // console.log(res, "名称获取");
            this.tableDatalist = res.data.records;
          });
    },
  },
};
</script>

<style scoped>
.box_flex_r .el-divider--horizontal {
  margin-top: 0px;
  margin-bottom: 10px;
}

.box_flex {
  display: flex;
}

.box_flex_l {
  width: 300px;
}

.box_flex_l .el-divider--horizontal {
  margin-bottom: 10px;
}

.box_flex_r {
  width: 100%;
  margin-left: 20px;
}

.box_flex_l_box_title {
  margin: 0px 0px 10px 10px;
}

.block {
  text-align: center;
  margin-top: 10px;
  /* margin:0px auto; */
}

.el-tree {
  padding-bottom: 20px;
  padding-top: 10px;
}

.info_sel_r_group {
  margin-left: 80px;
}

.info_sel_r_group_hou {
  margin-left: 95px;
}

.flex_btn {
  width: 100px;
}

.flex_btn button {
  margin: 10px 50px;
  height: 90px;
}

.top_dialog .el-divider--horizontal {
  margin-top: 0px;
  margin-bottom: 10px;
}

.top_dialog /deep/ .el-dialog {
  margin-top: 5vh !important;
}

.dialog_tab_l {
  margin-left: 20px;
}

.dialog_tab_btn {
  margin: 10px 20px 0px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.dialog_tab_btn div {
  margin-top: 20px;
  margin-bottom: 20px;
}

.dialog_tab_r_title {
  height: 45px;
  line-height: 45px;
}

.dialog_tab_r_title span:nth-child(2) {
  margin-left: 50px;
}

.dialog-footer button:nth-child(1) {
  margin-right: 50px;
}

.aside_box {
  width: 200px;
  height: 50vh;
  background: #fff;
  padding-top: 10px;
  overflow: hidden;
  overflow-y: auto;
}

.wi100 /deep/ .el-table__header {
  width: 100%;
}

.query {
  padding-left: 30px;
  padding-right: 30px;
}
</style>
